<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>加载图片</title>
  <style>
    canvas {
      border: 1px solid #333;
    }
  </style>
</head>

<body>
  <canvas width="200" height="300"></canvas>
  <p>
    <button>保存</button>
  </p>


</body>
<script>
  let canvas = document.querySelector("canvas")
  let ctx = canvas.getContext("2d")

  let img = new Image()
  img.src = "/images/boy.png"
  img.onload = function () {
    ctx.drawImage(img, 0, 0, img.width / 3, img.height / 3)
  }

  //保存图片
  let button = document.querySelector("button")
  button.addEventListener("click", function () {
    let dataURL = canvas.toDataURL()
    let link = document.createElement("a")
    link.href = dataURL
    link.download = "帅哥"

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

  })

</script>

</html>